<?php
/*
Cogumelo v0.1 - Map-Experience
Copyright (C) 2008 Innoto Gestión para el Desarrollo Social S.L. <mapinfo@map-experience.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*/



Class FormProc {
	public $dataArray;
	public $errorArray;

	//
	function __construct($key, $msg)
	{
		// create errors array
		$this->errorArray = array('key' => $key, 'errorlist' => null , 'msg' => $msg);
		
		// init data array
		$this->dataArray = array();
	}

	
	//
	//	Add variable, types and restrictions
	//
	function addInput($id, $msg, $data, $type, $required=false, $maxlength=false, $minlength=false, $maxvalue=false, $minvalue=false)
	{
		$this->dataArray[$id] = array(
			'id' => $id,
			'msg' => $msg,
			'data' => $data,
			'type' => $type,
			'required' => $required,
			'maxlenght' => $maxlength,
			'minlenght' => $minlength,
			'maxvalue' => $maxvalue,
			'minvalue' => $minvalue
		);
	}
	
	//
	//	Add manual errors
	//
	function addError($id, $msg) {
		if(!$this->errorArray['errorlist'])
			$this->errorArray['errorlist'] = array();
		
		$err = array();
		$err['id'] = $id;
		$err['msg'] = $msg;
		$this->errorArray['errorlist'][] = $err;

	}

	//
	//	Change Main error
	//
	function changeMainError($msg) {
		$this->errorArray['msg'] = $msg;
	}

	//
	//	Set errorlist = 1 (exist a general error in the form)
	//
	function setErrorListTrue() {
		$this->errorArray['errorlist'] = 1;
	}	
	
	//
	//	Add errors to errorArray reseting it before
	//
	function validate() {
		foreach($this->dataArray as $reg) {
			if(!$this->chkform($reg['data'], $reg['type'], $reg['required'], $reg['maxlenght'], $reg['minlenght'],	$reg['maxvalue'], $reg['minvalue'])) 
				$this->addError($reg['id'],$reg['msg']);
		}
	}
	
	//
	//	dump array data (to write or update)
	//
	function dumpData(){
		$arrayDump = array();
		
		foreach($this->dataArray as $datareg)
			$arrayDump[$datareg['id']] = $datareg['data'];
			
		return $arrayDump;
	}

	//
	//	Return true if validation have problems
	//
	function haveErrors() {
		if($this->errorArray['errorlist'] == null)
			return false;
		else
			return true;
	}
	
	//
	//	Return error Array
	//
	function dumpErrors() {
		return $this->errorArray;
	}
	
	//
	//	Check data from a form
	//	
	private function chkform($data, $type, $required, $maxlength, $minlength, $maxvalue, $minvalue)
	{
		// if $minlenght is false and data is null check is valid
	   if($required == false && ($data =='' || !$data))
			return true;
		
	   switch($type)
	   {
		   case 'STRING': // Check if it is a string
		   				if(strlen($data) <= $maxlength && strlen($data) > 0)
						 return(true);	              
		                break;   
		   case 'YESNO': // Check if it is a "Yes" or "No" value
		   				if($data == "On" || $data == "Off")
						 return(true);	              	                     	                   
		                break;
		   case 'INT':   // Check if it is a integer with a mex length
		   				if(preg_match('/^[\d]+$/',$data) && (strlen($data)<=$maxlength))
						 return(true);	              	                     	                   
		                break;
		   case 'INTMAXMIN':   // Check if it is a integer with a max and min value
		   				if(preg_match('/^[\d]+$/',$data) && ($data<=$maxlength) && ($data>=$minlength))
						 return(true);	              	                     	                   
		                break;
		   case 'LAT':   // Check if it is a decimal latitude value
		   				if(preg_match('/^[+|-]?[\d]{1,2}\.?[\d]*$/',$data) && (strlen($data)<=20)) //Max 20 chars
						 return(true);	              	                     	                   
		                break;                                                                    
		   case 'LON':   // Check if it is a decimal longitude value
		   				if(preg_match('/^[+|-]?[\d]{1,3}\.?[\d]*$/',$data) && (strlen($data)<=20)) //Max 20 chars
						 return(true);	              	                     	                   
		                break;   
		   case 'EMAIL':   // Check if it is a email direction
		   				if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/',$data) && strlen($data)<=255) //should be max 255 chars
						 return(true);	              	                     	                   
		                break;
		   case 'DATE':   // Check if it is a Date (DD-MM-YYYY / DD-MM-YY)
		   				if(strlen($data)<=10)
						 return(true);	              	                     	                   
		                break;         
		   case 'DNI':   // Check if it is a real DNI, NIF or NIE ID
		   				
		   				if($this->check_spanishID($data))
						 return(true);	              	                     	                   
		                break;
		   case 'PASSWD': // Check if it is a string
		   				if(strlen($data) <= 12 && strlen($data) >= 4)
						 return(true);              
		                break;  
		    case 'FLOAT':   // Check if it is a decimal latitude value
		   				if(preg_match('/^[\d]+[\.|,]?[\d]*$/',$data) && (strlen($data)<=$maxlength) && (strlen($data) > 0)) 
						 return(true);	              	                     	                   
		                break;                                                                              
	   }
	
	   return(false); // wrong data received
	}

	//
	//	Checking the smanish ID
	//	
	private function check_spanishID($form)
	{
				
		//remove all non standard chars
		$form = preg_replace( '/[^0-9A-Z]/i', '', $form);
		 
	
		// Is a NIF or NIE?
		if (preg_match('/[TX]?[0-9][A-Z]/i', $form))
		{	
	
			//Remove X if it is a NIE
			$form = preg_replace('/^[TX]/i', '', $form);
	
			// Add one 0 if is NIE or a small NIF
			$form = substr("0".$form, -9, 9);
			
	
			//check the letter of DNI or NIE
			$stack = 'TRWAGMYFPDXBNJZSQVHLCKE';
			$pos = substr($form, 0, 8) % 23;
			if (strtoupper( substr($form, 8, 1) ) == substr($stack, $pos, 1) )
			return true;
		}
		// It is a CIF
		else if (preg_match('/[A-HK-NPQS][0-9]{7}[A-J0-9]/i', $form)) //CIF
		{
	
			//summ all even digits
			$sum = 0;
			for ($i=2; $i<strlen($form)-1; $i+=2)
			{
				$sum += substr($form, $i, 1);
			}
			// x2 all odd position digits and sum all of them
			for ($i=1; $i<strlen($form)-1; $i+=2)
			{
				$t = substr($form, $i, 1) * 2;
				//Agregate the multiply result to the sum of the digits
				$sum += ($t>9)?($t-9):$t;
			}
			 
			//Rest to 10 the last digit of the sum
			$control = 10 - ($sum % 10);
			 
			//the control can be a numbber or letter
			if ( substr($form, 8, 1) == $control ||
			strtoupper(substr($form, 8, 1)) == substr('JABCDEFGHI', $control, 1 ))
			return true;
		}
		return false;
	}
	
}



?>